By default, When we create thread is implicitly foreground thread, foreground thread keeps application is alive as long as any one of foreground thread is active where as background thread do not. When all foreground thread is terminated then background thread implicitly terminated.
Foreground and background does not affect to each other.
Example:
To creating Foreground and Background thread writes the following code.
using System.Threading;
namespace ForegroundThread
{
class Program
{
static voidMain(string[] args)
{
// Create ThreadA object
Thread back= newThread(newThreadStart(ChildThreadA));
// Create ThreadB object
Thread fore= newThread(newThreadStart(ChildThreadB));
// Set ThreadB as background thread
back.IsBackground= true;
back.Start();
fore.Start();
Thread.CurrentThread.Name= "Main";
for (inti=0; i<20; i++)
{
if (i==5)
fore.Abort(); //Abort Foreground thread
Console.WriteLine(Thread.CurrentThread.Name);
}
}
public staticvoidChildThreadA()
{
for (inti=0; i<10; i++)
{
Console.WriteLine("Child thread A:");
}
}
public staticvoidChildThreadB()
{
for (inti=0; i<10; i++)
{
Console.WriteLine("Child thread B:");
}
}
}
}
In above program after terminating of foreground thread the application will run until main thread is not terminated after terminating main thread application will be terminate.
Output:

Leave Comment
1 Comments